<template>
  <div style="display: none">
    <div
      style="display: flex; flex-direction: column"
      ref="pdf-print"
      id="pdfPrint"
      v-print="pdfPrint"
    ></div>
  </div>
</template>

<script>
import axios from "axios";
import pdfjsLib from "pdfjs-dist";
import { getOrderTransportPdf } from "@/api/transport/index";
export default {
  props: ["wayBillCodes"],
  data() {
    return {
      pdfPrint: {
        id: "pdfPrint",
        popTitle: "打印快递单",
      },
    };
  },
  watch: {
    wayBillCodes: {
      handler: "print",
      immediate: true,
    },
  },
  methods: {
    async print() {
      if (!this.$refs["pdf-print"]) {
        return;
      }
      this.$refs["pdf-print"].innerHTML = "";
      const pdfList = await this.batchGetExpressPdfUrl(this.wayBillCodes);
      // const pdfUrls = await this.batchPrintExpressUrl(pdfList);
      const images = await this.batchPdfToImage(pdfList);
      // 渲染image
      images.forEach((image) => {
        image.forEach((img) => {
          const imgBox = document.createElement("div");
          imgBox.style.position = "relative";
          imgBox.style.width = "100%";
          imgBox.style.height = "auto";
          imgBox.style.paddingTop = "100%";
          const imgElement = document.createElement("img");
          imgElement.src = img;
          imgElement.style.width = "100%";
          imgElement.style.height = "100%";
          imgElement.style.position = "absolute";
          imgElement.style.top = "0";
          imgElement.style.left = "0";
          imgBox.appendChild(imgElement);
          this.$refs["pdf-print"].appendChild(imgBox);
        });
      });
      this.$emit("success");
      this.$refs["pdf-print"].click();
    },

    // 批量获取快递面单pdf
    async batchGetExpressPdfUrl(wayBillCodes) {
      const requestList = await Promise.all(
        wayBillCodes.map((wayBillCode) => {
          return getOrderTransportPdf(wayBillCode);
        })
      );
      return requestList.map((res) => {
        return res.data;
      });
    },

    // 批量获取打印信息
    async batchPrintExpressUrl(pdfList) {
      const requestList = await Promise.all(
        pdfList.map(async (pdf) => {
          return await this.getPrintInfo(pdf);
        })
      );
      return requestList.map((url) => {
        return url;
      });
    },

    // 通过快递单获取打印信息
    getPrintInfo(pdf) {
      return new Promise((resolve, reject) => {
        axios({
          method: "GET",
          url: pdf,
          responseType: "blob",
        })
          .then((res) => {
            let blob = new Blob([res.data], { type: "application/pdf" });
            resolve(URL.createObjectURL(blob));
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    // 批量转换pdf为image
    async batchPdfToImage(pdfUrls) {
      const requestList = await Promise.all(
        pdfUrls.map((pdfUrl) => {
          return this.pdfToImage(pdfUrl);
        })
      );
      return requestList.map((images) => {
        return images;
      });
    },

    // 转换pdf为image
    pdfToImage(pdfUrl) {
      return new Promise(async (resolve, reject) => {
        const pdf = await pdfjsLib.getDocument(pdfUrl);
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        const images = [];

        // 循环遍历每一页pdf，将其转成图片
        for (let i = 1; i <= pdf._pdfInfo.numPages; i++) {
          // 获取pdf页
          const page = await pdf.getPage(i);

          // 获取页的尺寸
          const viewport = page.getViewport({ scale: 4 });

          // 设置canvas的尺寸
          canvas.width = viewport.width;
          canvas.height = viewport.height;

          // 将pdf页渲染到canvas上
          await page.render({
            canvasContext: context,
            viewport: viewport,
          }).promise;
          images.push(canvas.toDataURL("iamge/jpeg", 1.0));
        }
        return resolve(images);
      });
    },
  },
};
</script>
